package com.gosling.cloudspace.tools;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import com.gosling.cloudspace.common.constants.CommonConstants;
import com.gosling.cloudspace.common.exception.CommonException;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lihonglin
 * @date 2024/11/5 下午4:15
 */
@Slf4j
public class AESUtil {

    private final static AES aes = new AES(Mode.ECB, Padding.PKCS5Padding, CommonConstants.AES_SECRET_KEY.getBytes());

    /**
     * AES 加密操作
     *
     * @param content 待加密内容
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content) {
        if (StrUtil.isBlank(content)) {
            return content;
        }
        return aes.encryptBase64(content);
    }

    /**
     * AES 解密操作
     *
     * @param content
     * @return
     */
    public static String decrypt(String content) {
        if (StrUtil.isBlank(content)) {
            return content;
        }
        String decryptContent = "";
        try {
            decryptContent = aes.decryptStr(content);
        } catch (Exception e) {
            log.error("AES解密异常:{},content:{}", e.getMessage(), content);
        }

        return decryptContent;
    }


    /**
     * AES 加密操作  处理链接参数base64会被转义问题
     *
     * @param content 待加密内容
     * @return 返回Hex转码后的加密数据
     */
    public static String encryptHex(String content) {
        if (StrUtil.isBlank(content)) {
            return content;
        }
        return aes.encryptHex(content);
    }



    /**
     * 调用方 提供密钥
     *
     * @param content
     * @param key
     * @return
     */
    public static String encrypt(String content, String key) {
        if (StrUtil.isBlank(content)) {
            return content;
        }
        if (StrUtil.isBlank(key)) {
            throw new CommonException("密钥不能为空");
        }
        AES aes = new AES(Mode.ECB, Padding.PKCS5Padding, key.getBytes());
        return aes.encryptBase64(content);
    }


    public static String decrypt(String content, String key) {
        if (StrUtil.isBlank(content)) {
            return content;
        }
        String decryptContent = "";
        try {
            AES aes = new AES(Mode.ECB, Padding.PKCS5Padding, key.getBytes());
            decryptContent = aes.decryptStr(content);
        } catch (Exception e) {
            log.error("AES解密异常:{},content:{}", e.getMessage(), content);
        }

        return decryptContent;
    }


}
